﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;

namespace VMwareEnabler.Model
{
    public class VMLauncher
    {
        private static readonly string[] pospaths = new string[2]; // = { "%programfiles%/VMware/VMware Player/vmplayer.exe", "%programfiles(x86)%/VMware/VMware Player/vmplayer.exe" };
        private static VMLauncher instance = null;
        public static VMLauncher Instance { get { if (instance == null) instance = new VMLauncher(); return instance; } }

        private VMLauncher()
        {
            pospaths[0] = Environment.ExpandEnvironmentVariables("%programfiles%/VMware/VMware Player/vmplayer.exe");
            pospaths[1] = Environment.ExpandEnvironmentVariables("%programfiles(x86)%/VMware/VMware Player/vmplayer.exe");
        }

        public void Launch()
        {
            if (String.IsNullOrEmpty(config.Default.vmpath))
            {
                Debug.WriteLine("Didn't find the path in settings");
                findVMware();
            }

            Process vmware = new Process();
            
            ProcessStartInfo si = new ProcessStartInfo(config.Default.vmpath);
            si.Arguments = "-U";
            vmware.StartInfo = si;
            vmware.EnableRaisingEvents = true;

            vmware.Exited += new EventHandler((object sender, System.EventArgs args) =>
                {
                    ViewModel.MainViewModel mvm = new ViewModel.ViewModelLocator().Main;
                    mvm.Disable();
                    Debug.WriteLine("Disabling services and net devices because VM has been closed");
                }
            );

            vmware.Start();

        }

        private static void findVMware()
        {
            Debug.WriteLine("Looking for VMware in regular paths");

            //Look for VMware on regular paths
            string path = null;
            foreach (string s in pospaths)
            {
                if (File.Exists(s))
                {
                    path = s;
                    Debug.WriteLine("Found VMware in path {0}", s);
                    config.Default.vmpath = s;
                    config.Default.Save();
                    return;
                }
            }

            //We must not have found it
            Debug.WriteLine("Couldn't find VMware on any known paths. Please help me find it.");
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.DefaultExt = ".exe";
            ofd.Filter = "Executable files (.exe)|*.exe";
            ofd.InitialDirectory = "C:\\";
            ofd.Multiselect = false;

            bool? result = ofd.ShowDialog();

            if (result == true) config.Default.vmpath = ofd.FileName;
            config.Default.Save();
            return;
        }
    }
}